const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const router = express.Router();

// 确保 assets 文件夹存在
const assetsDir = path.join(__dirname, '../assets');
if (!fs.existsSync(assetsDir)) {
  fs.mkdirSync(assetsDir, { recursive: true });
}

// Multer 配置，用于文件上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, assetsDir);
  },
  filename: function (req, file, cb) {
    const ext = path.extname(file.originalname);
    cb(null, 'bg-' + Date.now() + ext);
  }
});

const upload = multer({ 
  storage: storage,
  fileFilter: function (req, file, cb) {
    const filetypes = /jpeg|jpg|png|gif|webp/;
    const mimetype = filetypes.test(file.mimetype);
    const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
    if (mimetype && extname) {
      return cb(null, true);
    }
    cb(new Error('Error: File upload only supports the following filetypes - ' + filetypes));
  }
});

// GET /api/backgrounds - 获取所有背景图片
router.get('/', (req, res) => {
  fs.readdir(assetsDir, (err, files) => {
    if (err) {
      console.error("Could not list the directory.", err);
      return res.status(500).json({ message: 'Failed to read images directory' });
    }
    const imageFiles = files.filter(file => /\.(jpg|jpeg|png|gif|webp)$/i.test(file));
    const imageUrls = imageFiles.map(file => `/assets/${file}`);
    res.json(imageUrls);
  });
});

// POST /api/backgrounds/upload - 上传背景图片
router.post('/upload', upload.single('background'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({ message: 'No file uploaded' });
  }
  res.json({ url: `/assets/${req.file.filename}` });
});

// DELETE /api/backgrounds/:filename - 删除背景图片
router.delete('/:filename', (req, res) => {
  const filename = req.params.filename;
  if (!filename) {
    return res.status(400).json({ message: 'Invalid filename' });
  }

  const filePath = path.join(assetsDir, filename);

  // 安全性检查，确保文件在 assets 目录中
  if (path.dirname(filePath) !== assetsDir) {
      return res.status(400).json({ message: 'Invalid path' });
  }

  fs.unlink(filePath, (err) => {
    if (err) {
      console.error(`Failed to delete ${filePath}`, err);
      return res.status(500).json({ message: 'Failed to delete image' });
    }
    res.status(200).json({ message: 'Image deleted successfully' });
  });
});

module.exports = router;
